﻿using MediatR;
using RBAC.Domain;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.SlaughterCommand;
using Swork03_28.Domain.TraceableInfos;

namespace Swork03_28.Api.Application.CommandHandlers.SlaughterCommandHandler
{
    public class SlaughterCreateCommandHandler : IRequestHandler<SlaughterCreateCommand, int>
    {
        private readonly IRepository<Slaughter> _slaughter;
        private readonly IRepository<UserInfo> _userinfo;

        public SlaughterCreateCommandHandler(IRepository<Slaughter> slaughter, IRepository<UserInfo> _userinfo)
        {
            _slaughter = slaughter;
            this._userinfo = _userinfo;
        }

        public async Task<int> Handle(SlaughterCreateCommand request, CancellationToken cancellationToken)
        {
            var info = await _slaughter.GetValues(x => x.BatchId == request.BatchId);
            var data = info.FirstOrDefault();
            var uname = await _userinfo.GetAsync(request.UserId);
            if (data == null)
            {
                return await _slaughter.CreateAsync(new Slaughter()
                {
                    Id = request.Id,
                    BatchId = request.BatchId,
                    Aptitude = request.Aptitude,
                    BeginData = request.BeginData,
                    Certification = request.Certification,
                    Counterpoise = request.Counterpoise,
                    FinishData = request.FinishData,
                    CreateBy = uname.Name,
                    CreateDate = DateTime.Now,
                    UpdateBy = null,
                    UpdateDate = null,
                });
            }
            else
            {
                data.Id = request.Id;
                data.BatchId = request.BatchId;
                data.Aptitude = request.Aptitude;
                data.BeginData = request.BeginData;
                data.Certification = request.Certification;
                data.Counterpoise = request.Counterpoise;
                data.FinishData = request.FinishData;
                data.CreateBy = request.CreateBy;
                data.CreateDate = request.CreateDate;
                data.UpdateBy = uname.Name;
                data.UpdateDate = DateTime.Now;
            };
            return await _slaughter.UpdateAsync(data);
        }
    }
}
